package com.ziyun.erp.web.modules.goods.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.netflix.discovery.converters.Auto;
import com.service.goods.constant.GoodsResult;
import com.service.model.quote.constant.AttributeValueType;
import com.service.model.quote.constant.OemCategoryType;
import com.service.quote.module.factory.model.FactoryQuoteInfo;
import com.service.quote.module.quote.model.QuoteDto;
import com.service.quote.module.quote.model.QuoteResult;
import com.utility.JsonUtils;
import com.utility.New;
import com.ziyun.erp.common.utils.GoodsPriceUtils;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.goods.VO.FastPriceVo;
import com.ziyun.erp.modules.goods.VO.PrintPriceVo;
import com.ziyun.erp.modules.goods.VO.VerifyPriceVo;
import com.ziyun.erp.modules.goods.entity.GoodsProductEntity;
import com.ziyun.erp.modules.goods.entity.QuoteVO;
import com.ziyun.erp.modules.goods.service.GoodsAttributeService;
import com.ziyun.erp.modules.goods.service.GoodsProductService;
import com.ziyun.erp.modules.goodsCategory.entity.GoodsCategoryEntity;
import com.ziyun.erp.modules.goodsCategory.service.GoodsCategoryService;
import com.ziyun.erp.modules.goodsImage.entity.GoodsImageEntity;
import com.ziyun.erp.modules.goodsImage.service.GoodsImageService;
import com.ziyun.erp.modules.store.storeGoodsCategory.entity.StoreGoodsCategoryTwdEntity;
import com.ziyun.erp.modules.store.storeGoodsCategory.service.StoreGoodsCategoryTwdService;
import io.renren.common.utils.StringUtil;
import io.renren.common.utils.UserUtil;
import io.renren.common.validator.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ziyun.erp.modules.goods.entity.GoodsEntity;
import com.ziyun.erp.modules.goods.service.GoodsService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 商品表
 *
 * @author
 * @email
 * @date 2018-08-21 08:46:29
 */
@RestController
@RequestMapping("goods/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsProductService goodsProductService;

    @Autowired
    private GoodsAttributeService goodsAttributeService;

    @Autowired
    private GoodsImageService goodsImageService;

    @Autowired
    private GoodsCategoryService goodsCategoryService;

    @Autowired
    private com.service.goods.api.GoodsService goodsService2;
    @Autowired
    private StoreGoodsCategoryTwdService storeGoodsCategoryTwdService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    // @RequiresPermissions("goods:goods:list")
    public R list(@RequestParam Map<String, Object> params) {
//        goodsService.queryGoodsPage(page,params);
        PageUtils page = goodsService.queryPage(params);
        //图文宝分类列表只查询goods表已有的数据
        List<StoreGoodsCategoryTwdEntity> twbCategoryList = storeGoodsCategoryTwdService.selectTwbList(params);
        Map<String, Object> map = new HashMap<>();
        map.put("twbCategoryList", twbCategoryList);
        return R.ok().put("page", page).put("userData", map);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{goodsId}")
//    @RequiresPermissions("goods:goods:info")
    public R info(@PathVariable("goodsId") Long goodsId) {
//        GoodsEntity goodsProperty = goodsService.getAllGoodsProperty(goodsId);
////        GoodsEntity goods = goodsService.selectById(goodsId);
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("goods_id",goodsId);
//        map.put("disabled",0);
//        //获得并处理产品数据
//        List<GoodsProductEntity> goodsProductList = getAndHandlerProducts(goodsProperty, map);
//        if(goodsProductList.size()>0){
//            goodsProductService.setCraftValues(goodsProperty,goodsProductList.get(0));
//        }
//        //关联设计服务
//        GoodsEntity designGood = null;
//        if(StringUtils.isNotBlank(goodsProperty.getRelateDesignIds())) {
//            designGood = goodsService.selectById(goodsProperty.getRelateDesignIds());
//        }
////        //默认图片和详细图片处理返回
//        List<GoodsImageEntity> imageList = null;
//        if(StringUtils.isNotBlank(goodsProperty.getImageUrls())){
//            imageList = goodsImageService.selectImageEntity(goodsProperty.getImageUrls());
//        }
//        List<GoodsImageEntity> infoList = null;
//        if(StringUtils.isNotBlank(goodsProperty.getInfoUrls())){
//            infoList = goodsImageService.selectImageEntity(goodsProperty.getInfoUrls());
//        }
//        GoodsImageEntity videoEntity = null;
//        if(StringUtils.isNotBlank(goodsProperty.getVideoUrl())){
//            videoEntity = goodsImageService.selectById(goodsProperty.getVideoUrl());
//        }
//        //获得原规格属性选项数据
//        Map<String, Object> attributeAndCraftData = goodsService.getAttributeAndCraftData(goodsProperty);
        Integer sellerId = 1;
        return goodsService.getAllGoodsProperty(goodsId, sellerId);
    }

    /**
     * 按map获得并处理products数据
     *
     * @param goodsProperty
     * @param map
     * @return
     */
    private List<GoodsProductEntity> getAndHandlerProducts(GoodsEntity goodsProperty, HashMap<String, Object> map) {
        List<GoodsProductEntity> goodsProductList = goodsProductService.selectByMap(map);
        if (goodsProductList.size() > 0) {
            String craftOptionIds = goodsProductList.get(0).getCraftOptionIds();
            String optionIds = goodsProductList.get(0).getOptionIds();
            String attributeNames = goodsAttributeService.getAttributeNamesByOptionIds(optionIds);
            String craftNames = goodsAttributeService.getCraftNamesByCraftOptionIds(craftOptionIds);
            goodsProperty.setAttributeNames(attributeNames);
            goodsProperty.setCraftNames(craftNames);
        }
        //设置goodsProductList,将option对象赋值进入goodsProduct
        goodsProductService.setOptionByGoodsProductList(goodsProductList);
//        goodsProductService.setCraftOptionByGoodsProductList(goodsProductList);
        //方案二
        return goodsProductList;
    }

    /**
     * 保存-->方法弃置
     */
    @RequestMapping("/save")
    //@RequiresPermissions("goods:goods:save")
    public R save(@RequestBody GoodsEntity goods) {
        goodsService.insert(goods);

        return R.ok();
    }

    /**
     * 修改--编辑商品保存
     */
    @RequestMapping("/update")
    //@RequiresPermissions("goods:goods:update")
    public R update(@RequestBody GoodsEntity goods) {
        ValidatorUtils.validateEntity(goods);

        goodsService.updateGoods(goods, UserUtils.getCurentUser().getUserId());//全部更新
        goodsService.loadGoodsCacheEvent(goods.getGoodsId());
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("goods:goods:delete")
    public R delete(@RequestBody Long[] goodsIds) {
        goodsService.deleteBatchIds(Arrays.asList(goodsIds));
        return R.ok();
    }

    /**
     * 查询设计服务商品
     */
    @RequestMapping("/designList")
    public R designList(@RequestParam Map<String, Object> params) {
        Map<String, Object> map = New.hashMap();
        //注,这里的1964是设计服务分类的顶级分类id
//        map.put("parent_category_id",1964);
//        map.put("disabled",0);
//        List<GoodsCategoryEntity> goodsCategoryEntities = goodsCategoryService.selectByMap(map);
        params.put("userId", 1L);
        PageUtils page = goodsService.queryPageNew(params);
        return R.ok().put("page", page);
    }

    /**
     * 商品关联设计服务
     */
    @RequestMapping("/addDesign/{goodId}/{designId}")
    public R addDesign(@PathVariable("goodId") String goodId, @PathVariable("designId") String designId) {
        Integer nGoodId = StringUtil.getRequestParamInteger(goodId);
        Integer nGesignId = StringUtil.getRequestParamInteger(designId);
        goodsService.addDesign(nGoodId, nGesignId);
        return R.ok();
    }

    /**
     * 信息
     */
    @RequestMapping("/designInfo/{designId}")
//    @RequiresPermissions("goods:goods:info")
    public R designInfo(@PathVariable("designId") Long designId) {
        GoodsEntity designGood = goodsService.selectById(designId);
        return R.ok().put("designGood", designGood);
    }

    /**
     * 发布商品
     */
    @RequestMapping("/pushGood")
    public R pushGood(@RequestBody GoodsEntity goods) {
        if (StringUtils.isBlank(goods.getCreateName())) {
            goods.setCreateName(UserUtils.getCurentUser().getUsername());
        }
        goods.setSelf(true);
        goods.setSellerId(1);
        goodsService.pushGood(goods);
        goodsService.loadGoodsCacheEvent(goods.getGoodsId());
        return R.ok();
    }

    /**
     * updateStatus更新spu状态
     */
    @RequestMapping("/updateStatus/{goodsId}/{status}")
    public R updateStatus(@PathVariable("goodsId") Long goodsId, @PathVariable("status") String status) {
        goodsService.updateStatus(goodsId, status, UserUtils.getCurentUser().getUserId());
        goodsService.loadGoodsCacheEvent(goodsId);
        return R.ok();
    }

    /**
     * 发布商品
     */
    @RequestMapping("/pushQuoteGood")
    public R pushQuoteGood(@RequestBody QuoteVO quoteVO) {
        System.out.println(quoteVO);
        quoteVO.getGoodsEntity().setSelf(true);
        quoteVO.getGoodsEntity().setSellerId(1);
        quoteVO.getGoodsEntity().setCreateName(UserUtils.getCurentUser().getUsername());

        for (int i = 0; i < quoteVO.getQuoteProductBaseInfoVOList().size(); i++) {
            quoteVO.getQuoteProductBaseInfoVOList().get(i).setCreateUser(UserUtils.getCurentUser().getUsername());
        }
        goodsService.pushQuoteGood(quoteVO);
        goodsService.loadGoodsCacheEvent(quoteVO.getGoodsEntity().getGoodsId());
        return R.ok();
    }

    /**
     * 根据三级分类,查询所有的商品
     */
    @RequestMapping("/goodsList")
    public R goodsList(@RequestBody Map map) {
        List<GoodsEntity> goodsEntities = goodsService.selectByMap(map);
        return R.ok().put("spuTableData", goodsEntities);
    }

    /**
     * 刷新全部缓存
     */
    @RequestMapping("/refreshAllCache")
    public R refreshAllCache() {
        //先做一下权限校验
        List<Long> roleIdList = UserUtils.getCurentUser().getRoleIdList();
        System.out.println(roleIdList);
        goodsService.loadAllGoodsCacheEvent();
        return R.ok();
    }


    /**
     * 刷新全部缓存
     */
    @RequestMapping("/solveBug")
    public R solveBug() {
        //先做一下权限校验
        goodsService.solveBug();
        return R.ok();
    }

    /**
     * 工艺校验价格
     */
    @RequestMapping("/verifyCraftPrice")
    public R verifyCraftPrice(@RequestBody VerifyPriceVo verifyPriceVo) {
//        System.out.println(verifyPriceVo);
        //先做一下权限校验
        String result = goodsService.verifyCraftPrice(verifyPriceVo, 1L);
        return R.ok().put("result", result);
    }

    /**
     * 工艺校验价格
     */
    @RequestMapping("/quotePrice")
    public R quotePrice(@RequestBody String ids) {
//        System.out.println(ids);
        //先做一下权限校验
//        String result = goodsService.verifyCraftPrice(verifyPriceVo);
        String result = goodsService.quotePrice(ids, 1);
        return R.ok().put("result", result);
    }

    /**
     * 商务印刷机器校验
     */
    @RequestMapping("/verifyPrintPrice")
    public R verifyPrintPrice(@RequestBody PrintPriceVo printPriceVo) {
        Integer factoryId = 1;
        String result = goodsService.verifyPrintPrice(printPriceVo, factoryId);
        return R.ok().put("result", result);
    }

    /**
     * 数码快印组合商品计价校验
     */
    @RequestMapping("/verifyFastPrice")
    public R verifyFastPrice(@RequestBody List<FastPriceVo> fastPriceVoList) {
        System.out.println(fastPriceVoList);
        Integer sellerId = 1;
        String result = goodsService.verifyFastPrice(fastPriceVoList, sellerId);
        return R.ok().put("result", result);
    }


    /**
     * 发布商品
     */
    @RequestMapping("/updateQuoteGood")
    public R updateQuoteGood(@RequestBody QuoteVO quoteVO) {
        quoteVO.getGoodsEntity().setSellerId(1);
//        quoteVO.getGoodsEntity().setCreateName(UserUtils.getCurentUser().getUsername());
        for (int i = 0; i < quoteVO.getQuoteProductBaseInfoVOList().size(); i++) {
            quoteVO.getQuoteProductBaseInfoVOList().get(i).setUpdateUser(UserUtils.getCurentUser().getUsername());
            quoteVO.getQuoteProductBaseInfoVOList().get(i).setUpdateDate(new Date());
            quoteVO.getQuoteProductBaseInfoVOList().get(i).setCreateUser(quoteVO.getGoodsEntity().getCreateName());
        }
        goodsService.editQuoteGood(quoteVO);
        goodsService.loadGoodsCacheEvent(quoteVO.getGoodsEntity().getGoodsId());
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/hideGoods")
    public R hideGoods(@RequestBody Long goodsId) {
        goodsService.hideGoods(goodsId, UserUtils.getCurentUser().getUserId());
        goodsService.loadGoodsCacheEvent(goodsId);
        return R.ok();
    }

    /**
     * 改变发布人归属
     */
    @RequestMapping("/opMarkGoods/{goodsId}/{mark}")
    public R opMarkGoods(@PathVariable("goodsId") Integer goodsId, @PathVariable("mark") Boolean mark) {
        goodsService.opMarkGoodsByGoodsId(goodsId, mark);
        return R.ok();
    }

    /**
     * 修改审核状态
     */
    @RequestMapping("/examineGoods/{goodsId}/{examine}")
    public R examineGoods(@PathVariable("goodsId") Integer goodsId, @PathVariable("examine") Integer examine) {
        goodsService.examineGoods(goodsId, examine);
        if (examine.intValue() == 1) {
            goodsService.loadGoodsCacheEvent(Long.valueOf(goodsId));
        }
        return R.ok();
    }

    /**
     * 批量改价
     */
    @RequestMapping("changePrice/upload")
    public R Excel(HttpServletRequest request, MultipartFile file) {
        if (file != null) {
            List<GoodsProductEntity> goodsProductList = null;
            try {
                InputStream inputStream = file.getInputStream();
                goodsProductList = GoodsPriceUtils.analysisExcle(inputStream);
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        return R.ok("导入成功");
    }

    /**
     *
     */
    @RequestMapping("/countPrice")
    public R countPrice(@RequestBody List<Map<String, Object>> list) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Boolean erpSellerFlag = (Boolean) list.get(0).get("erpSellerFlag");
        Integer categoryId1 = Integer.valueOf(String.valueOf(list.get(0).get("categoryId")));
        for (int i = 0; i < list.size(); i++) {
            Integer partsId = (Integer) list.get(i).get("partsId");
            List ids = (List) list.get(i).get("ids");
            //根据ids去查询获得
            Map<String, Object> map = New.hashMap();
            if (list.size() != 1) {
                map.put("partsId", partsId);
            } else {
                map.put("categoryId", partsId);
            }
            map.put("ids", org.apache.commons.lang.StringUtils.join(ids, ","));
            Map<String, Object> params = New.hashMap();
            params.put("params", map);
            Map<String, Object> resultMap = goodsCategoryService.countPrice(params);
            Boolean flag = (Boolean) resultMap.get("flag");
            if (flag) {
                resultList.add(resultMap);
            }
        }
        QuoteDto quoteDto = new QuoteDto();
        Map map2 = (Map) resultList.get(0);
        String categoryType = (String) map2.get("categoryType");
        OemCategoryType oemCategoryType = OemCategoryType.valueOf(categoryType);
        quoteDto.setCategoryType(oemCategoryType);
        //处理数据
        Map<Integer, Map> newAttributesMap = New.hashMap();
        Map<Integer, Map<AttributeValueType, Integer>> lastAttributesMap = New.hashMap();
        for (int i = 0; i < resultList.size(); i++) {
            //map1是一个部件返回的数据信息
            Map map1 = (Map) resultList.get(i);
            Map attributesMap = (Map) map1.get("attributesMap");
            List list1 = (List) attributesMap.get("list");
            Integer categoryId = (Integer) attributesMap.get("categoryId");
            Map<String, Object> temp = New.hashMap();
            Map<AttributeValueType, Integer> newTemp = New.hashMap();
            for (int j = 0; j < list1.size(); j++) {
                Map map = (Map) list1.get(j);
                Integer optionId = Integer.parseInt(String.valueOf(map.get("optionId")));
                String attributeValueKey = (String) map.get("attributeTypeValue");
                temp.put(attributeValueKey, optionId);
                AttributeValueType attributeValueType = AttributeValueType.valueOf(attributeValueKey);
                newTemp.put(attributeValueType, optionId);
            }
            newAttributesMap.put(categoryId, temp);
            lastAttributesMap.put(categoryId, newTemp);
        }
        quoteDto.setAttributesMap(lastAttributesMap);
//        quoteDto.setErpSellerFlag(erpSellerFlag);
        quoteDto.setErpSellerFlag(true);
        quoteDto.setCategoryId(categoryId1);
        quoteDto.setFactoryId(1L);
        System.out.println(JsonUtils.object2String(quoteDto));
        GoodsResult<QuoteResult> factoryQuote = goodsService2.findFactoryQuote(quoteDto);
        if (factoryQuote != null) {
            if (factoryQuote.getData() != null) {
                List<FactoryQuoteInfo> factoryQuoteInfos = factoryQuote.getData().getFactoryQuoteInfos();
                if (factoryQuoteInfos.size() > 0) {
                    if (factoryQuoteInfos.size() > 1) {
                        return R.error("异常信息,默认商品算价找到多个工厂!");
                    }
                    Double totalPrice = factoryQuoteInfos.get(0).getTotalPrice();
                    return R.ok().put("result", totalPrice);
                } else {
                    return R.ok().put("result", "默认商品算价没有找到工厂");
                }
            } else {
                return R.ok().put("result", "默认商品算价没有找到工厂");
            }
        }
        return R.error("默认商品算价回调返回值为空");
    }

    /**
     * 添加图文宝分类
     *
     * @param goods
     * @return
     */
    @RequestMapping("/goodsTwbUpdate")
    public R goodsTwbUpdate(@RequestBody GoodsEntity goods) {
        return goodsService.goodsTwbUpdate(goods);
    }

    /**
     * 远程搜索
     *
     * @param params
     * @return
     */
    @RequestMapping("/search")
    public R search(@RequestBody Map<String, Object> params) {
        List<StoreGoodsCategoryTwdEntity> twbCategoryList = storeGoodsCategoryTwdService.selectTwbList(params);
        return R.ok().put("twbCategoryList", twbCategoryList);
    }

    /**
     * 图文宝问题图片数据修复
     */
    @RequestMapping("/twbGoodsImageBug")
    public R twbGoodsImageBug() {

        goodsService.twbGoodsImageBug();
        return R.ok();
    }

}
